import axios from "axios";
import {getItem} from "@/utils/auth";
import store from "@/store";
import {Message, Notification} from 'element-ui';

const api = axios.create({
    baseURL:process.env.VUE_APP_API_ROOT,
    withCredentials:false,
    maxRedirects:5,
    timeout:8000,
})

// 请求拦截器
api.interceptors.request.use(
    config => {
        if (store.state.token){
            config.headers['like-admin'] = store.state.token
        }else{
            config.headers['like-admin'] = getItem('admin')
        }

        return config

    },
    error => {

        return Promise.reject(error)
    })


// 相应拦截器
api.interceptors.response.use(response=>{
    const code = response.data.code
    switch (code){
        case 200:{
            if (/upload/.test(response.config.url)){
                return response.data
            }else{
                return response.data
            }
        }
        case 500:{
            if (window.navigator && navigator.onLine === true) {
                Message.error( response.data.msg ? response.data.msg : '系统异常')

            } else {
                this.$t('h.A007')
            }
            return Promise.reject(response.data)
        }
        default:{
            if (window.navigator && navigator.onLine === true) {
                Notification.error(
                    {
                        position: 'top-left',
                        message: response.data.msg,
                        title: '警告',
                    })
            } else {

            }
            return Promise.reject(response.data)
        }
    }
},
    error => {
        return Promise.reject(error)
    })

export default api